package com.lambert.ginkgo.config;

import com.lambert.ginkgo.WebClientTemplate;
import com.lambert.ginkgo.properties.WebClientProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import javax.net.ssl.SSLException;
import java.time.Duration;
import java.util.Map;

/**
 * OpenAI 配置类，初始化专用的 WebClientTemplate
 */
@Configuration
@EnableConfigurationProperties(WebClientProperties.class)
public class OpenAIConfig {

    /**
     * 创建OpenAI专用的WebClientTemplate实例
     * 手动配置认证信息、超时和基础URL
     */
    @Bean
    @Qualifier("openaiWebClientTemplate")
    public WebClientTemplate openaiWebClientTemplate(OpenAIProperties properties, WebClientProperties defaultWebClientProperties) throws SSLException {
        // 1. 配置WebClientProperties
        WebClientProperties webClientProperties = properties.getWebClientProperties();
        if (webClientProperties == null) {
            webClientProperties = defaultWebClientProperties;
        }
        webClientProperties.setBaseUrl(properties.getBaseUrl());
        Map<String, String> defaultHeaders = webClientProperties.getDefaultHeaders();
        defaultHeaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + properties.getApiKey());
        defaultHeaders.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        // 2. 直接通过构造函数创建WebClientTemplate（根据实际构造参数调整）
        return new WebClientTemplate(webClientProperties);
    }
}
